/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.test
 * author:David
 * Date:2015年6月5日下午11:52:54
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.ext.myclassloader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author David since 2015年6月5日 下午11:52:54
 * @version
 * @since JDK 1.6
 */
public class MyClassLoader extends ClassLoader{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String srcPath = args[0];
		String destDir = args[1];
		try {
			System.out.println(srcPath);
			FileInputStream fis = new FileInputStream(srcPath);
			String destFileName = srcPath
					.substring(srcPath.lastIndexOf("\\") + 1);
			String destPath = destDir + "\\" + destFileName;
			FileOutputStream fos = new FileOutputStream(destPath);
			cypher(fis, fos);
			fis.close();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加密、解密函数
	 * 
	 * @param istream
	 * @param ostream
	 * @throws IOException
	 */
	private static void cypher(InputStream istream, OutputStream ostream)
			throws IOException {
		byte b = 0;
		while ((b = (byte) istream.read()) != -1) {
			ostream.write(b ^ 0xff);
		}

	}
	
	private String classDir;

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String classFileName = classDir + "\\"  + name.substring(name.lastIndexOf('.')+1) + ".class";
		try {
			FileInputStream fis = new FileInputStream(classFileName);
			ByteArrayOutputStream  bos = new ByteArrayOutputStream();
			cypher(fis,bos);
			fis.close();
			System.out.println("aaa");
			byte[] bytes = bos.toByteArray();
			return defineClass(bytes, 0, bytes.length);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public MyClassLoader(){
		
	}
	
	public MyClassLoader(String classDir){
		this.classDir = classDir;
	}
	
	
}
